<!-- 重新设定密码 -->
<template>
  <com-dialog class="reset-password-wp"
    v-model="visible"
    title="重新设定密码"
    width="800px"
    :is-center="false">
    <el-form class="this-form" ref="form" :model="form" :rules="rules" label-width="6em" label-position="right" size="medium">
      <el-form-item label="用户账号" prop="username">
        <el-input v-model="form.username" readonly placeholder="请输入用户账号" clearable></el-input>
      </el-form-item>
      <el-form-item label="登录密码" prop="password">
        <el-input v-model="form.password" placeholder="请输入登录密码" clearable></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmpassword">
        <el-input v-model="form.confirmpassword" placeholder="请重新输入登录密码" clearable></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button size="medium" @click="visible = false">取消</el-button>
      <el-button :loading="btnLoading" type="primary" size="medium" @click="submit()">确认</el-button>
    </div>
  </com-dialog>
</template>
<script>

import {user} from "@/config/api.js";

export default {
  data () {
    const checkNewPassword = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      btnLoading: false,

      // 表单
      form: {
        username: '', // 用户账号
        password: '', // 登录密码
        confirmpassword: '', // 确认密码
      },

      // 验证
      rules: {
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
        ],
        confirmpassword: [
          { required: true, message: "请重新输入登录密码", trigger: "blur" },
          { validator: checkNewPassword, trigger: 'blur'}
        ],
      }

    }
  },
  methods: {
    open (detail) {
      this.detail = detail;

      this.initForm(); // 初始化表单

      this.visible = true;
    },

    // 提交
    submit () {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return;
        }
        var param = this.$g.copy(this.form);
        param.id = this.detail.id;

        this.btnLoading = true;
        this.$put(user.changePassword, param).then(res => {
          this.btnLoading = false;
          if (res.success) {
            this.$message.success(res.message);
            this.$emit('reload');
            this.visible = false;
          }
        }).catch(() => {
          this.btnLoading = false;
        })
      })
    },

    // 初始化表单
    initForm () {
      for (var key in this.form) {
        this.form[key] = this.detail[key] || '';
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.reset-password-wp {
  .this-form {
    padding: 0 100px;
  } 
}
</style>